package com.bw.ivideoproject.live

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.SurfaceView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.bw.ivideoproject.R
import com.bw.ivideoproject.databinding.ActivityLiveBinding
import com.bw.lib_mvvm.BaseActivity
import io.agora.rtc2.ChannelMediaOptions
import io.agora.rtc2.ClientRoleOptions
import io.agora.rtc2.Constants
import io.agora.rtc2.IRtcEngineEventHandler
import io.agora.rtc2.RtcEngine
import io.agora.rtc2.RtcEngineConfig
import io.agora.rtc2.video.VideoCanvas


class LiveActivity : BaseActivity<ActivityLiveBinding>() {

    private val PERMISSION_REQ_ID = 22

    private var isBroadcastr = false


    override fun initView() {
        isBroadcastr = intent.getBooleanExtra("isBroadcastr", false)
    }

    override fun initData() {

    }

    override fun bindLayout(): Int {
        return R.layout.activity_live
    }

    // 填写你的项目在声网控制台中生成的 App ID。
    private val appId = "7dcd6d5a108d4c41b497290060f7b313"

    // 填写频道名称。
    private val channelName = "channel"

    // 填写声网控制台中生成的临时 Token。
    private val token = "007eJxTYHAOi44W/Phq/pulmvnSU/MSY7+zrdpxqNyh+/7yub+up55VYDBPSU4xSzFNNDSwSDFJNjFMMrE0N7I0MDAzSDNPMjY0Pla/Nq0hkJFh0lNhZkYGCATx2RmSMxLz8lJzGBgAMb4ibg=="

    private var mRtcEngine: RtcEngine? = null

    private val mRtcEventHandler: IRtcEngineEventHandler = object : IRtcEngineEventHandler() {
        // 监听频道内的远端主播，获取主播的 uid 信息。
        override fun onUserJoined(uid: Int, elapsed: Int) {
            runOnUiThread { // 从 onUserJoined 回调获取 uid 后，调用 setupRemoteVideo，设置远端视频视图。
                setupRemoteVideo(uid)
            }
        }

        override fun onJoinChannelSuccess(channel: String?, uid: Int, elapsed: Int) {
            super.onJoinChannelSuccess(channel, uid, elapsed)
            runOnUiThread {
                showMsg("join channel success")
            }
        }

        override fun onUserOffline(uid: Int, reason: Int) {
            super.onUserOffline(uid, reason)
            showMsg("User offline: $uid")
        }
    }

    private fun initializeAndJoinChannel() {

        val config = RtcEngineConfig()
        config.mContext = baseContext
        config.mAppId = appId
        config.mEventHandler = mRtcEventHandler
        mRtcEngine = RtcEngine.create(config)

        if(isBroadcastr){
            mRtcEngine?.enableVideo()
            val surfaceView = SurfaceView(baseContext)
            binding.localVideoViewContainer.addView(surfaceView)
            mRtcEngine?.setupLocalVideo(VideoCanvas(surfaceView,VideoCanvas.RENDER_MODE_FIT,0))
            mRtcEngine?.startPreview()
        }

        val options = ChannelMediaOptions()
        if(isBroadcastr){
            options.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER
        }else{
            options.clientRoleType = Constants.CLIENT_ROLE_AUDIENCE
        }

        options.channelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING
        options.publishMicrophoneTrack = true
        options.publishCameraTrack = true
        options.autoSubscribeAudio = true
        options.autoSubscribeVideo = true
        mRtcEngine?.joinChannel(token,channelName,0,options)
    }

    private fun setupRemoteVideo(uid: Int) {
        val surfaceView = RtcEngine.CreateRendererView(baseContext)
//        surfaceView.setZOrderMediaOverlay(true)
        binding.localVideoViewContainer.addView(surfaceView)
        mRtcEngine!!.setupRemoteVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, uid))
    }

    private fun getRequiredPermissions(): Array<String> {
        // 判断 targetSDKVersion 31 及以上时所需的权限
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            arrayOf<String>(
                Manifest.permission.RECORD_AUDIO,  // 录音权限
                Manifest.permission.CAMERA,  // 摄像头权限
                Manifest.permission.READ_PHONE_STATE,  // 读取电话状态权限
                Manifest.permission.BLUETOOTH_CONNECT // 蓝牙连接权限
            )
        } else {
            arrayOf<String>(
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA
            )
        }
    }

    private fun checkPermissions(): Boolean {
        for (permission in getRequiredPermissions()) {
            val permissionCheck = ContextCompat.checkSelfPermission(this, permission)
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                return false
            }
        }
        return true
    }

    protected override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (checkPermissions()) {
            initializeAndJoinChannel()
        } else {
            ActivityCompat.requestPermissions(this, getRequiredPermissions(), PERMISSION_REQ_ID)
        }

    }

    // 系统权限申请回调
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (checkPermissions()) {
            initializeAndJoinChannel()
        }
    }

    protected override fun onDestroy() {
        super.onDestroy()
        if (mRtcEngine != null) {
            // 停止本地视频预览
            mRtcEngine!!.stopPreview()
            // 离开频道
            mRtcEngine!!.leaveChannel()

            // 销毁引擎
            RtcEngine.destroy()
        }
    }

}